﻿using System;

namespace MikadoShooter
{
    [Serializable]
    public class Level
    {
        public LevelData CurrentLevel { get; private set; }
        public int LevelNr { get; private set; }

        [NonSerialized]
        private int colors;
        public int Colors { get { return colors; } }

        [NonSerialized]
        private int lines;
        public int Lines { get { return lines; } }

        [NonSerialized]
        private readonly LevelMessageBox messageBox;
        public LevelMessageBox MessageBox { get { return messageBox; } }

        public Level()
        {
            messageBox = new LevelMessageBox();

            if (!LoadLevel())
                CreateNewLevel(1);  //Start from level 1
        }

        public Vector4Target NextLevel()
        {
            CreateNewLevel(++LevelNr);
            messageBox.IsNeedNewBuffer = true;

            return CurrentLevel.Targets;
        }

        public Vector4Target Restart()
        {
            LoadLevel(false);

            return CurrentLevel.Targets;
        }

        private bool LoadLevel(bool silent = true)
        {
            LevelData levelData;

            if (FileHelper.Load(out levelData, silent))
            {
                CurrentLevel = levelData;
                LevelNr = CurrentLevel.Level.LevelNr;
                InitLevel();
                return true;
            }
            return false;  
        }

        private void CreateNewLevel(int levelnr)
        {
            LevelNr = levelnr;
            InitLevel();

            //Create targets
            Vector4Target targets = new Vector4Target(DrawTarget.CalcVerticals(Lines), this);

            //Set level
            CurrentLevel = new LevelData(targets,this);

            //Save level on disk
            FileHelper.Save(CurrentLevel, false);
        }

        private void InitLevel()
        {
            colors = 3 + ((LevelNr-1) % 4);
            lines = 10 + LevelNr*2;
        }
    }
}